/**
 * @author : dormi330
 * @version : 1.0
 * description : 文件描述
 */

package org.dormi.learn.utils;

import org.apache.commons.io.IOUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ResourceUtils {

    /**
     * 加载资源
     *
     * @param fileName 资源名称
     * @return 资源
     */
    public static Properties loadProperties(String fileName) {
        Properties prop = new Properties();
        ClassLoader classLoader = ResourceUtils.class.getClassLoader();
        try (InputStream inputStream = classLoader.getResourceAsStream(fileName)) {
            prop.load(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace(System.out);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }

        return prop;
    }

    /** 读取资源文件 -> string */
    public static String loadRes2String(String fileName) {
        String result = null;
        ClassLoader classLoader = ResourceUtils.class.getClassLoader();
        try {
            result = IOUtils.toString(classLoader.getResourceAsStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /** 将资源文件转换为对象, 便于测试 */
    public static <T> T loadRes2Object(String path, Class<T> clazz) {
        String str = loadRes2String(path);
        return JsonSerializer.jsonToObj(str, clazz);
    }
}
